define(['angular', 'app.directives','directives/common/ueditor2','directives/common/laydate','filters/common/base','services/jewellery/jewellery_service'], function (angular, directives) {
    'use strict';

    //商品
    directives.directive("goodsList", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: function () {
                return "/app/partial/jewellery/goods_list.html";
            },
            link: function ($scope) {
                $scope.showType=false;
                $scope.showStyle=false;
                $scope.showPX=false;

                $scope.goodsParam={};

                $scope.currentPage=1;
                $scope.itemsPerPage=9;
                var getList = function () {
                    jewelleryService.webGetGoodsList($scope.currentPage, $scope.itemsPerPage, $scope.goodsParam, function (data) {
                        $scope.goodsList = data.data.list;
                        if( $scope.currentPage==1){
                            $scope.totalItems = data.data.count;
                        }
                    }, function (data) {
                        alert(data.message);
                    });
                };
                getList();
                $scope.pageChanged=function(){
                    getList();
                };

                $scope.searchGoods=function(){
                    $scope.currentPage=1;
                    getList();
                };
                $scope.typeOneClick=function(typeOne){
                    if(typeOne!=undefined){
                        $scope.goodsParam.typeOne=typeOne.id;
                    }else{
                        $scope.goodsParam.typeOne="";
                    }
                    serachGoodByTypeOne(typeOne);
                }
                $scope.typeClick=function(type){
                    if(type!=undefined){
                        $scope.goodsParam.type=type.id;
                    }else{
                        $scope.goodsParam.type="";
                    }
                    serachGoodByType(type);
                }
                $scope.styleClick=function(style){
                    if(style!=undefined){
                        $scope.goodsParam.gstyle=style.id
                    }else{
                        $scope.goodsParam.gstyle="";
                    }
                    serachGoodByStyle(style)
                }
                $scope.pxClick=function(px){
                    if(px!=undefined){
                        $scope.goodsParam.px=px.id;
                    }else{
                        $scope.goodsParam.px="";
                    }
                    $scope.currentPage=1;
                    getList();
                }
                var serachGoodByTypeOne=function(typeOne){
                    if(typeOne!=undefined&&typeOne!=null){
                        $scope.showType=true;
                        $scope.showStyle=false;
                        $scope.showPX=false;
                        $scope.typeList=typeOne.typeList;
                        console.info($scope.typeList);
                        $scope.currentPage=1;
                        getList();
                    }else{
                        $scope.showType=false;
                        $scope.showStyle=false;
                        $scope.showPX=false;
                        $scope.goodsParam.type="";
                        $scope.goodsParam.gstyle="";
                        $scope.goodsParam.px="";
                        getList();
                    }

                }
                var serachGoodByType=function(type){
                     if(type!=undefined&&type!=null) {
                         $scope.styleList = type.styleList;
                         $scope.showType = true;
                         $scope.showStyle = true;
                         $scope.showPX = false;
                         $scope.currentPage = 1;
                         getList();
                     }else{
                         $scope.showStyle = false;
                         $scope.showPX = false;
                         $scope.goodsParam.gstyle="";
                         $scope.goodsParam.px="";
                         getList();
                     }
                 }
                var serachGoodByStyle=function(gstyle){
                    if(gstyle!=undefined&&gstyle!=null) {
                        $scope.pxList = gstyle.pList;
                        $scope.showType = true;
                        $scope.showStyle = true;
                        $scope.showPX = true;
                        $scope.currentPage = 1;
                        getList();
                    }else{
                        $scope.showPX = false;
                        $scope.goodsParam.px="";
                        getList();
                    }
                }

                jewelleryService.getGoodsTypeList(function(data){
                    $scope.typeOneList=data.data;
                },function(data){});






            }
        }
    }]);
    //商品详细信息
    directives.directive("goodsDetail", ['$stateParams','CurrentUser','jewelleryService','$uibModal', function ($stateParams,CurrentUser,jewelleryService,$uibModal) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/goods_detail.html",
            link: function ($scope) {
                $scope.currentPage=1;
                $scope.itemsPerPage=2;
                var error=function(err){
                    layer.alert(err.message);
                }
                $scope.goodsNum = 1;
                $scope.goodsWeight = {
                    "minWeight": 1,
                    "maxWeight": 1,
                    "jgf": 0
                };
                //获取商品信息
                jewelleryService.webGetGoodsDeatil($stateParams.id,function(data){
                    $scope.goods=data.data;
                    $scope.goodsWeightList=data.data.goodsWeightList;
                },error);
                //获取商品图片
                jewelleryService.webGetGoodsPic($stateParams.id,function(data){
                    $scope.imgUrlList=data.data;
                },error);
                //获取商品评价
                var getEvaList=function(){
                    jewelleryService.webGoodsEvaList($stateParams.id,$scope.currentPage, $scope.itemsPerPage,function(data){
                        $scope.evaluateList=data.data.list;
                        if( $scope.currentPage==1){
                            $scope.totalItems = data.data.count;
                        }
                        console.info($scope.evaluateList);
                    },error);
                }
                getEvaList();
                $scope.pageChanged=function(){
                    console.info($scope.currentPage);
                    getEvaList();
                };

                //查询购物车
                var getCartByUGId=function(goodsId, goodsWeightId){
                    jewelleryService.webCartByUGId(goodsId, goodsWeightId, function(data) {
                        if(data.data != null) {
                            $scope.uCart = data.data;
                            $scope.goodsNum = $scope.uCart.number;
                        }
                    }, error);
                }
                //选择规格
                $scope.goodWeightCheck = false;
                //选择规格
                $scope.selectWeight = function(goodsWeight) {
                    $scope.goodWeightCheck = true;
                    $scope.goodsWeight = goodsWeight;
                    getCartByUGId($scope.goods.id, goodsWeight.id); //查询是否存在于购物车
                }
                //加入购物车
                $scope.shoppingCart = function() {
                    if(!$scope.goodWeightCheck) {
                        alert("请选择商品规格");
                        return;
                    }
                    $scope.shopcart = {
                        "goodsId": $scope.goods.id,
                        "goodsWeightId": $scope.goodsWeight.id,
                        "number": $scope.goodsNum,
                        "content": $scope.content
                    };
                    jewelleryService.addShopCart($scope.shopcart, function(data) {
                        alert("加入购物车成功！");
                        window.close();
                    }, error);
                }
                $scope.pingJiaXiangQing='xq';
                $scope.pingJiaXiangQingClick=function(type){
                    $scope.pingJiaXiangQing=type;
                }
            }

        }
    }]);
    //购物车查询
    directives.directive("shoppingcartList", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: function () {
                return "/app/partial/jewellery/shoppingcart_list.html";
            },
            link: function ($scope) {
                var error=function(err){
                    layer.alert(err.message);
                }
                $scope.showYHQ=false;
                //购物车信息
                var getCartList = function () {
                    jewelleryService.getWebCartList(function (data) {
                        $scope.cart=data.data;
                       if( $scope.cart.length!=0){
                           $scope.showYHQ=true;
                       }
                    }, function (data) {
                        alert(data.message);
                    });
                };
                getCartList();
                //优惠券信息
                var getCouponList=function(){
                    jewelleryService.getWebCouponList(function(data){
                        $scope.couponList = data.data;
                        console.info($scope.couponList);
                    },function(data){
                        alert(data.message);
                    });
                }
                getCouponList();
                //计算总价格
                $scope.totalPrice=0;
                $scope.sum=0;
                $scope.dealPrice=0;
                $scope.totalWeight=0;
                var calculationTotalPrice=function(){
                    var price=0;
                    var sum=0;
                    var totalWeight=0;
                    var goodsCheckeds = getCheckBoxRes("checkedGoods");
                    var goodsCheckedList = [];
                    angular.forEach(goodsCheckeds, function (data) {
                        var checkgoods=JSON.parse(data);
                        goodsCheckedList.push(checkgoods);
                        price=price+(checkgoods.price+checkgoods.jgf)*(checkgoods.minWeight+checkgoods.maxWeight)/2*checkgoods.number;
                        totalWeight=totalWeight+(checkgoods.minWeight+checkgoods.maxWeight)/2*checkgoods.number;
                        sum=sum+checkgoods.number;
                    });
                    $scope.totalPrice=price;
                    $scope.dealPrice=price;
                    $scope.totalWeight=totalWeight;
                    $scope.sum=sum;
                    if($scope.str!=0){
                        if($scope.totalPrice>$scope.cou.coupon.dealPrice){//选择优惠券以后，又删减商品数量了，
                            $scope.dealPrice=$scope.totalPrice-$scope.cou.coupon.discountPrice;
                        }

                    }
                }
                //修改购物车商品的数量
                $scope.goodsNumberChange=function(goods){
                    jewelleryService.updateWebSCartNumber(goods.id,goods.number,function(data){
                        calculationTotalPrice();
                    },error);
                }
                //删除购物车商品
               var deleteGoodsById=function(goodsId,goodsWeightId){
                    jewelleryService.deleteWebSCartGoods(goodsId,goodsWeightId,function(data){
                        angular.forEach($scope.cart, function(goods,index) {
                            if(goods.id==goodsId){
                                $scope.cart.splice(index,1);
                            }
                        });
                    },error);
                }
                //删除操作
                $scope.deleteGoods=function(goodsId,goodsWeightId){
                    deleteGoodsById(goodsId,goodsWeightId);
                    calculationTotalPrice();
                }
                var getCheckBoxRes=function(name){
                    var rdsObj   = document.getElementsByName(name);
                    var checkVal = new Array();
                    var k        = 0;
                    for(var i = 0; i < rdsObj.length; i++){
                        if(rdsObj[i].checked){
                            checkVal[k] = rdsObj[i].value;
                            k++;
                        }
                    }
                    return checkVal;
                }

                //点选触发事件
                $scope.checkChange=function(){
                    calculationTotalPrice();
                }
                //全选
                $scope.checkAllBtn=function(){
                    calculationTotalPrice();
                }
                //优惠券操作
                $scope.cou={};
                $scope.str=0;

                $scope.checkCoupon=function(data){
                    $scope.cou=data;
                    $scope.str=1;
                }
                $scope.noUseCou=function(){
                    $scope.str=0;
                }
                //确认使用优惠券
                $scope.couUse=function(){
                    if($scope.str==0){
                        alert("此次交易将不使用任何优惠券");
                    }else{
                        if($scope.dealPrice>=$scope.cou.coupon.dealPrice){
                            $scope.dealPrice=$scope.totalPrice-$scope.cou.coupon.discountPrice;
                            alert("此次订单优惠后易额为："+$scope.dealPrice);
                        }else{
                            alert("不满足使用条件");
                        }
                    }
                   // document.getElementById("coupon_select_box").style.display="none";
                }
                //提交订单
                $scope.addToOrder=function(){
                    if($scope.totalWeight==0){
                        alert("请选择订单商品");
                        return;
                    }
                    document.getElementById('addToOrder').disabled = true;
                    var goodsCheckeds = getCheckBoxRes("checkedGoods");
                    var orderDetail={};
                    orderDetail.totalPrice=$scope.totalPrice;//总价格
                    orderDetail.totalWeight=$scope.totalWeight;//总重量
                    orderDetail.dealPrice=$scope.dealPrice;//加以价格（优惠后）
                    orderDetail.content=$scope.content;//订单备注信息

                    if($scope.str==0){
                        orderDetail.ifCoupon=false;
                    }else{//之前选择过优惠券
                        if($scope.totalPrice<$scope.cou.coupon.dealPrice){//选择优惠券以后，又删减商品数量了，
                            orderDetail.ifCoupon=false;
                        }else{
                            orderDetail.ifCoupon=true;
                            orderDetail.couponId=$scope.cou.couponId;
                            orderDetail.couNumber=$scope.cou.number-1;//优惠券的剩余数量
                        }

                    }
                    var goodsList=[];
                    angular.forEach(goodsCheckeds, function (data) {
                        var checkgoods=JSON.parse(data);
                        var goods={};
                        goods.goodsId=checkgoods.id;
                        goods.dealPrice=checkgoods.price;
                        goods.dealNum=checkgoods.number;
                        goods.content=checkgoods.content;
                        goods.perWeight=(checkgoods.minWeight+checkgoods.maxWeight)/2;
                        goods.goodsWeightId=checkgoods.goodsWeightId;
                        goodsList.push(goods);
                    });
                    orderDetail.goods=goodsList;
                    jewelleryService.addWebOrderDetail(orderDetail,function(data){
                        alert("提交订单成功");
                        getCartList();
                    },error);
                }

            }
        }
    }]);
    directives.directive("orderList", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/orderList.html",
            link: function ($scope) {
                var error=function(err){
                    layer.alert(err.message);
                }
                $scope.orderParam={};
                $scope.currentPage=1;
                $scope.itemsPerPage=10;
                $scope.orderList=null;
                //获取订单信息
                var getList=function(){
                    jewelleryService.getOrderList($scope.orderParam,$scope.currentPage, $scope.itemsPerPage,function(data){
                        var orderList=$scope.orderList=data.data.list;
                        if( $scope.currentPage==1){
                            $scope.totalItems = data.data.count;
                        }
                        angular.forEach(orderList, function(order) {
                            var total=0;
                            angular.forEach(order.goods, function(goods) {
                                total+=goods.dealNum;
                                order.total=total;
                            });
                        });
                    },function(data){
                        alert(data.message);
                    });
                };
                $scope.showOrderId="";
                $scope.showOrderClick=function(orderId){
                    if($scope.showOrderId==orderId){
                        $scope.showOrderId="";
                    }else{
                        $scope.showOrderId=orderId;
                    }
                }
                getList();
                $scope.pageChanged=function(){
                    getList();
                };
                $scope.searchOrderList=function(){
                    $scope.currentPage=1;
                    getList();
                };
                jewelleryService.getGoogsTypeList(function(data){
                    $scope.gTypeList=data.data;
                },error);
                $scope.getTypeIfContain=function(id,ids){
                    var flag=false;
                    for(var i=0;i<ids.length;i++){
                        if(id==ids[i]){
                            flag=true;
                            return flag;
                        }
                    }
                    return flag;
                }
                $scope.typeOneClick=function(item){
                    $scope.typeOneChecked=item.id;//一级选中
                    $scope.typeChecked="";//二级选中
                    $scope.typeList=item.typeList;
                    $scope.curTypeOne=item;
                    $scope.curType={};
                }

                $scope.typeClick=function(item){
                    $scope.typeChecked=item.id;
                    $scope.curType=item;
                    $scope.curTypeOne={};
                }
                //删除订单
                $scope.deleteOrder=function(order){
                    if((order.status=="1"&&order.payStatus=="1")||(order.status=="0"&&order.payStatus=="0")){
                        //交易完成可以删除---逻辑删除
                        jewelleryService.deleteOrderStatus(order.orderId,function(data){
                            angular.forEach($scope.orderList,function(item,index){
                                if(order.orderId==item.orderId){
                                    $scope.orderList.splice(index,1);
                                }
                            })
                        },function(data){
                            alert(data.message);
                        });
                    }else{
                        //交易正在进行 不允许删除
                        alert("正在交易，不允许删除！");
                    }
                }
            }
        }
    }]);

    //评价
    directives.directive("evaluate", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/evaluate.html",
            link: function ($scope) {
                var error=function(err){
                    alert(err.message);
                };
                jewelleryService.getOrderById($stateParams.id, function(data) {
                    $scope.order=data.data;
                    $scope.goodsList = data.data.goods;
                    angular.forEach($scope.goodsList, function(goods) {
                        jewelleryService.getEvaluate($stateParams.id,goods.goodsId,function(data){
                            $scope.evaluate=data.data;
                            if($scope.evaluate != null&&$scope.evaluate !=""){
                                document.getElementById(goods.goodsId).innerHTML=$scope.evaluate.content;
                            }
                        },error);
                    });
                }, error);
                $scope.publish=function(){
                    var goods=$scope.order.goods;
                    var orderId=$scope.order.orderId;
                    var list=[];
                    for(var i=0;i<goods.length;i++){
                        var content=document.getElementById(goods[i].goodsId).value;
                        $scope.evaluate={"orderId":orderId,"goodsId":goods[i].goodsId ,"content":content};
                        if(content!=null&&content!=""){
                            list.push($scope.evaluate);
                        }
                    }
                    jewelleryService.addEvaluate(list,function(data){
                        alert("评价成功！");
                    },error);
                };
             /*   jewelleryService.getGoogsTypeList(function(data){
                    $scope.gTypeList=data.data;
                },error);
                $scope.getTypeIfContain=function(id,ids){
                    var flag=false;
                    for(var i=0;i<ids.length;i++){
                        if(id==ids[i]){
                            flag=true;
                            return flag;
                        }
                    }
                    return flag;
                }
                $scope.typeOneClick=function(item){
                    $scope.typeOneChecked=item.id;//一级选中
                    $scope.typeChecked="";//二级选中
                    $scope.typeList=item.typeList;
                    $scope.curTypeOne=item;
                    $scope.curType={};
                }

                $scope.typeClick=function(item){
                    $scope.typeChecked=item.id;
                    $scope.curType=item;
                    $scope.curTypeOne={};
                }*/
            }
        }
    }]);
    //我的旧物
    directives.directive("myOldList", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/myOldList.html",
            link: function ($scope) {
                $scope.orderParam={};
                $scope.currentPage=1;
                $scope.itemsPerPage=3;
                var getList=function(){
                    jewelleryService.getOldList({},$scope.currentPage,$scope.itemsPerPage,function(data){
                        $scope.oldList=data.data.list;
                        if( $scope.currentPage==1){
                            $scope.totalItems = data.data.count;
                        }
                    },function(data){

                    });
                };
                getList();
                $scope.pageChanged=function(){
                    getList();
                };

                $scope.deleteOld=function (oldId) {
                    jewelleryService.deleteOld(oldId,function(){
                        alert("删除成功！");
                        getList();
                    },function () {
                        alert("删除失败！");
                    });
                }
            }
        }
    }]);

    //修改旧物
    directives.directive("oldGoodsUpdate", ['$stateParams','CurrentUser','jewelleryService', function ($stateParams,CurrentUser,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/oldGoodsUpdate.html",
            link: function ($scope) {
                $("#file-1").fileinput({
                    uploadUrl: "/dapi/upload/attachment", // you must set a valid URL here else you will get an error
                    allowedFileExtensions : ['jpg','jpeg', 'png','gif'],
                    overwriteInitial: false,
                    maxFileSize: 100000,
                    slugCallback: function(filename) {
                        return filename.replace('(', '_').replace(']', '_');
                    }
                }) .on("fileuploaded", function(event, data) {
                    if(data.response) {
                        $scope.picUrl=data.response.data;
                    }
                });

                $scope.currentPage=1;
                $scope.itemsPerPage=10;
                var error=function(err){
                    alert(err.message);
                }
                jewelleryService.getGType('2',function (data) {
                    $scope.typeList=data.data;
                },function () {

                });
                //删除商品展示图
                $scope.deleteIconUrl=function(id){
                    jewelleryService.deleteOldIconUrl(id,function(data){
                        alert("删除成功！");

                    },error)
                };
                //获取商品信息
                jewelleryService.getOldById($stateParams.id,function(data){
                    $scope.old=data.data;
                },error);
                //提交
                $scope.submitOld=function(){
                    if($scope.picUrl!=undefined&&$scope.picUrl!=""){
                        $scope.old.iconUrl=$scope.picUrl;
                        $scope.old.ifPic=1;
                    }
                    jewelleryService.updateOld($scope.old,function(data){
                        alert("修改成功");
                    },error)
                }
            }
        }
    }]);
    directives.directive("couponList", ['$q','$location','$stateParams','CurrentUser','$uibModal','jewelleryService', function ($q,$location,$stateParams,CurrentUser,$uibModal,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/couponList.html",
            link: function ($scope) {
                var error=function(err){
                    layer.alert(err.message);
                }
                jewelleryService.getUserCouponList(function(data){
                    $scope.couponList=data.data;
                },error);
            }
        }
    }]);

    //旧物详情
    directives.directive("oldGoodsDetail", ['$stateParams','CurrentUser','jewelleryService', function ($stateParams,CurrentUser,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: "/app/partial/jewellery/oldGoods_detail.html",
            link: function ($scope) {
                var error=function(err){
                    alert(err.message);
                }
                jewelleryService.getGType('2',function (data) {
                    $scope.typeList=data.data;
                },function () {

                });
                jewelleryService.getGStyle(function (data) {
                    $scope.gstyleList=data.data;
                },function () {

                });
                //获取商品信息
                jewelleryService.getOldById($stateParams.id,function(data){
                    $scope.old=data.data;
                },error)
            }
        }
    }]);

    //添加旧物页面
    directives.directive("oldGoodsAdd", ['$stateParams','jewelleryService', function ($stateParams,jewelleryService) {
        return {
            restrict: 'E',
            scope: {},
            replace: true,
            templateUrl: function () {
                return "/app/partial/jewellery/oldGoodsAdd.html";
            },
            link: function ($scope) {
                $scope.picUrl="";
                $("#file-1").fileinput({
                    uploadUrl: "/dapi/upload/attachment", // you must set a valid URL here else you will get an error
                    allowedFileExtensions : ['jpg','jpeg', 'png','gif'],
                    overwriteInitial: false,
                    maxFileSize: 100000,

                    //allowedFileTypes: ['image', 'video', 'flash'],
                    slugCallback: function(filename) {
                        // console.error(filename);
                        return filename.replace('(', '_').replace(']', '_');
                    }
                }) .on("fileuploaded", function(event, data) {
                    if(data.response) {
                        $scope.picUrl=data.response.data;
                        //alert('处理成功');
                    }
                });

                jewelleryService.getGType('2',function (data) {
                    $scope.typeList=data.data;
                },function () {

                });
                $scope.addOld=function () {
                    if($scope.picUrl==undefined||$scope.picUrl==""){
                        alert("请上传图片");
                        return false;
                    }
                    $scope.old.ifPic=1;
                    $scope.old.iconUrl=$scope.picUrl;
                    jewelleryService.addOld($scope.old,function () {
                        alert("添加成功")
                        $scope.submitIsClick=false;
                    },function () {

                    });
                }
            }
        }
    }]);
});